const jwt = require('jsonwebtoken');
const jwtConfig = require('../config/default').jwt_config;

// 生成token
const generateToken = (payload = {}) =>
  jwt.sign(payload, jwtConfig.secret, { expiresIn: jwtConfig.expiresIn });

// 验证token
const verifyToken = token => {
  let decode;
  try {
    decode = jwt.verify(token, jwtConfig.secret);
  } catch (error) {
    decode =
      error['name'] == 'TokenExpiredError' ? 'expired token' : 'invalid token';
  }
  return decode;
};

module.exports = {
  generateToken,
  verifyToken
};
